const { ccclass, property } = cc._decorator;

@ccclass
export default class Breathing extends cc.Component {

    @property(cc.Float)
    duration: number = 1;

    @property(cc.Float)
    range: number = 0.98;

    @property(cc.Float)
    delay: number = 0.5;

    @property([cc.Node])
    follows: cc.Node[] = [];

    defaultScaleX: number;
    defaultScaleY: number;
    followsCount = 0;
    followsOffset: number[] = [];

    private range2: number;
    private tween1: cc.Tween = null;
    private tween2: cc.Tween = null;
    private tweenIsRuning: boolean;

    start() {
        this.defaultScaleX = this.node.scaleX;
        this.defaultScaleY = this.node.scaleY;
        this.followsCount = this.follows.length;
        for (let i = 0; i < this.followsCount; i++) {
            let follow = this.follows[i];
            this.followsOffset.push((follow.y - this.node.y) * this.node.scaleY);
        }
        this.createTween();
        this.tweenIsRuning = true;
        this.tween1.start();
    }

    update() {
        if (!this.tweenIsRuning) {
            this.tweenIsRuning = true;
            this.tween1.start();
            this.tweenIsRuning = true;
        }
        for (let i = 0; i < this.followsCount; i++) {
            let follow = this.follows[i];
            let followOffset = this.followsOffset[i];
            follow.y = this.node.y + followOffset * this.node.scaleY;
        }
    }

    private createTween() {
        this.range2 = 1 + 1 - this.range;
        this.tween1 = cc.tween(this.node).delay(this.delay).to(this.duration, { scaleX: this.defaultScaleX * this.range, scaleY: this.defaultScaleY * this.range2 }, { easing: 'sineInOut' }).call(() => {
            this.onTween1Finish();
        });
        this.tween2 = cc.tween(this.node).to(this.duration, { scaleX: this.defaultScaleX * this.range2, scaleY: this.defaultScaleY * this.range }, { easing: 'sineInOut' }).call(() => {
            this.onTween2Finish();
        });
    }

    /** 运行中修改该参数 */
    resetInfo(duration: number, range: number, delay: number) {
        this.duration = duration;
        this.range = range;
        this.delay = delay;
        if (this.tween1) {
            this.tween1.removeSelf();
        }
        if (this.tween2) {
            this.tween2.removeSelf();
        }
        this.createTween();
    }

    private onTween1Finish() {
        if (this.enabled) {
            this.tween2.start();
        } else {
            this.tweenIsRuning = false;
        }
    }

    private onTween2Finish() {
        if (this.enabled) {
            this.tween1.start();
        } else {
            this.tweenIsRuning = false;
        }
    }

}
